"""CORS（跨域资源共享）中间件"""

from fastapi.middleware.cors import CORSMiddleware
from typing import List, Dict, Union, Optional

from backend.common.config import config_manager
from backend.logger_setup import get_logger

logger = get_logger('cors_middleware')

def setup_cors(app):
    """设置CORS中间件
    
    Args:
        app: FastAPI应用实例
    """
    try:
        # 获取CORS配置 - 从api配置中获取
        cors_origins = config_manager.api.cors_origins
        
        # 配置CORS中间件
        app.add_middleware(
            CORSMiddleware,
            allow_origins=cors_origins,
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
            expose_headers=["*"],
            max_age=600
        )
        
        logger.info(f"CORS中间件已设置，允许的源: {cors_origins}")
    except Exception as e:
        logger.error(f"设置CORS中间件失败: {str(e)}")
        # 设置默认的CORS配置作为备选
        app.add_middleware(
            CORSMiddleware,
            allow_origins=["*"],  # 为了开发环境方便，默认允许所有源
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )
        logger.warning("已使用默认CORS配置")

__all__ = [
    'setup_cors'
]